#include<16f877a.h>
#device ADC=8
#include<stdlib.h>
#fuses HS,NOWDT,NOPROTECT,NOLVP
#use delay(clock=20000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)
unsigned int a=0;



//****************=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=- Hardware Defines -=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
sbit SENSOR = P1^0; //sensor is connected to this pin
unsigned int beatms;
float bpm;
char buf[20];
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=- Main Program -=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void main()
{
// -=-=- Intialize variables -=-=-=
lcdInit();
// -=-=- Welcome LCD Message -=-=-=
lcdClear();
lcdGotoXY(0,0); // 1st Line of LCD
// "xxxxxxxxxxxxxxxx"
lcdPrint("DIGITAL HEART");
lcdGotoXY(0,1); // 2nd Line of LCD
// "xxxxxxxxxxxxxxxx"
lcdPrint("BEAT MONITOR");
beatms=0; // will store duration between two pulses
// -=-=- Program Loop -=-=-=
while(1)
{
while(SENSOR==0);// wait for high pulse from sensor
DelayNmS(10); // 10ms delay so that it does not listen to any noise
beatms = 10; // start counting beatms from 10ms since we have delay after pulse
while(SENSOR==1)// wait until signal is high
{
DelayNmS(1); //wait 1msec
beatms++; //keep incrementing counter each 1ms
}
while(SENSOR==0) //keep looping till signal goes back high, wait for next
{
DelayNmS(1); //wait 1msec
beatms++; //keep incrementing counter each 1ms
}
// beatms variable will now have time in ms between two high edge pulse
//lcdClear();
//lcdGotoXY(0,0);
//lcdPrint("HEART RATE : ");
bpm = 60000/beatms; // see document of #1157 for this calculation
if(bpm > 200)
{
//lcdGotoXY(0,1);
printf (buf, "Processing......"); // Invalid, Wait for next cycle
//cdPrint(buf);
} else {
//lcdGotoXY(0,1);
printf (buf, "%0.0f BPM", bpm); // Display reading in BPM
lcdPrint(buf);
}




//***********



/*void main()
{

while(1)
{
      if(input(PIN_D1) ==1)
      {
         a=a+1;
         //printf("high\n\r");
         if(input(PIN_D1)==0)
         //a++;
         //printf("low\n\r");

         a=a+1;
         printf("beat=%u\n\r",a);

      }

       delay_ms(500);
      /*if(a<50)
      {
       output_d(0x02);
      }
      else if(a>=50 && a<=100)
      {
         output_d(0x04);
      }
      else if(a>=100 && a<=150)
      {
        output_d(0x08);
      }
      else if(a>=150 && a<=200)
      {
         output_d(0x10);
      }
      else if(a>=200 && a<=250)
      {
         output_d(0x20);
      }
      */

}

}
